const bcrypt = require('bcrypt')
const {getUserInfo} = require('../service/user.service')

const {
  userFormateError,
  userAlreadyExited,
  userRegisterError,
  userDoesNotExist,
  userLoginError,
  invalidPassword,
} = require('../constant/err.type')

// 验证用户名和密码是否为空
const userValidator = async (ctx, next) => {
  const {user_name, pass_word} = ctx.request.body
  if(!user_name || !pass_word) {
    console.error('用户名或密码为空', ctx.request.body)
    ctx.response.body = userFormateError
    return
  }
  await next()
}

// 注册时验证用户名是否存在
const verifyUser = async (ctx, next)=> {
  const {user_name} = ctx.request.body

  try {
    const res = await getUserInfo({user_name})
    if(res && res.length > 0) {
      console.error('用户名已经存在', { user_name })
      ctx.response.body = userAlreadyExited
      return
    }
  } catch(err) {
    console.error('获取用户信息错误', err)
    ctx.response.body = userRegisterError
    return
  }
  await next()
}

// 密码加密
const crpytPassword = async (ctx, next)=> {
  const { pass_word } = ctx.request.body
  const saltRounds = 10
  // hash 保存的是密文
  const salt = bcrypt.genSaltSync(saltRounds)
  const hash = bcrypt.hashSync(pass_word, salt)

  ctx.request.body.pass_word = hash

  await next()
}

// 登陆时验证用户是否存在
const verifyLogin = async (ctx, next)=> {
  const {user_name, pass_word} = ctx.request.body
  try {
    const res = await getUserInfo({user_name})
    // 1、用户名不存在
    if(!res) {
      console.error('用户名不存在',{user_name})
      ctx.response.body = userDoesNotExist
      return
    }

    // 2、密码是否匹配
    if(!bcrypt.compareSync(pass_word, res[0].password)) {
      ctx.response.body = invalidPassword
      return
    }
  } catch(err) {
    console.log(err)
   return ctx.response.body = userLoginError
  }
  await next()
}
// 修改密码时，验证密码是否匹配
const verifyPass = async (ctx, next)=> {
  const {id, old_pass} = ctx.request.body
  try {
    const res = await getUserInfo({id})
    // 2、密码是否匹配
    if(!bcrypt.compareSync(String(old_pass), res[0].password)) {
      ctx.response.body = invalidPassword
      return
    }
  } catch(err) {
    console.log(err)
   return ctx.response.body = invalidPassword
  }
  await next()
}


module.exports = {
  userValidator,
  verifyUser,
  crpytPassword,
  verifyLogin,
  verifyPass
}
